@Library('jenkins-shared-library') _// 引入共享库
def jobName = "${env.JOB_NAME}"
def userJonString = "${params.TEST_PARAM}"
pipeline {
    agent none // 不指定全局代理
    stages {
        stage('Initialize') {
            steps {
                script {
                    def repositories = []
                    def isTimerTrigger = false
                    currentBuild.getBuildCauses().each { cause ->
                        def shortDescription = "${cause.shortDescription}"
                        if (shortDescription.contains('Started by timer')) {
                            isTimerTrigger = true
                        }
                    }
                    getDatabaseConnection(type:'GLOBAL') {
                            def result = sql(sql:  "SELECT * FROM project_info where project_name = '${jobName}';")
                            def jsonString = "${result[0].param}"
                        repositories = readJSON text: jsonString
                    }
                    def repositoriesUser = [:]
                    if (!isTimerTrigger) {
                        echo 'This build was triggered not by a timer.'
                        def repositoriesUser_ = readJSON text: userJonString
                        repositoriesUser_.each { repo ->
                            def repositoryName = "${repo.repositoryName}"
                            repositoriesUser[repositoryName] = repo
                        }
                    }
                    def parallelStages = [:]
                    def params = [:]
                    repositories.eachWithIndex { repo, index ->
                        def repositoryName = "${repo.repositoryName}"
                        if (repositoriesUser[repositoryName]) {
                             println "repositoriesUser: ${repositoriesUser[repositoryName]}"
                            println "branch: ${repositoriesUser[repositoryName].branch}"
                            repo.branch = getBuildTag("${jobName}", repo.url, repo.credentialsId, repositoriesUser[repositoryName].branch)
                        }else {
                            println "no branch"
                            repo.branch = getBuildTag("${jobName}",repo.url, repo.credentialsId, null)
                        }
                        for (build in repo.buildConfigs) {
                            def script = "${build.script}"
                            for (nodeLabel in build.nodeLabels) {
                                def node_id = "${repositoryName}-${index}-${nodeLabel}"
                                params[node_id] = repo
                                parallelStages[node_id] = {
                                    node("${nodeLabel}") {
                                        def str="@Library('jenkins-shared-library') _// 引入共享库 \n\n def node_id = '${node_id}' \n\n def param = getBuildParam(build_id:node_id, env:env) \n\n ${script}"
                                        println "str: ${str}"
                                        evaluate(str)
                                    }
                                }
                            }
                        }
                    }
                    env.package_time = System.currentTimeMillis()
                    env.paramString = groovy.json.JsonOutput.toJson(params)
                    print "$parallelStages"
                    parallel parallelStages
                }
            }
        }
    }

    post {
        success {
            script {
                dingtalk(
                        robot: 'ci',
                        type: 'MARKDOWN',
                        title: "success: ${env.JOB_NAME}",
                        text: [
                                '### 构建信息',
                                '---',
                                "- 项目名称 : ${env.JOB_NAME}",
                                "- 构建编号: <font color=#008000>${env.BUILD_ID}</font>",
                                "- 构建状态: **<font color=#008000>${currentBuild.result}</font>**",
                                "- 项目地址: [地址](${env.BUILD_URL})",
                                "- 构建日志: [日志](${env.BUILD_URL}console)",
                                '- 进入页面: [http://43.138.159.33:65004/](http://43.138.159.33:65004/)',
                                '',
                                '---',
                                "- 执行人: ${currentBuild.getBuildCauses().shortDescription[0]}",

                                '---',
                                "- 持续时间:${currentBuild.durationString}",

                                '---'
                        ]
                )
            }
        }
        failure {
            script {
                dingtalk(
                        robot: 'ci',
                        type: 'MARKDOWN',
                        title: "failure: ${env.JOB_NAME}",
                        text: [
                                '### 构建信息',
                                '---',
                                "- 项目名称 : ${env.JOB_NAME}",
                                "- 构建编号: <font color=#dd3238>${env.BUILD_ID}</font>",

                                "- 构建状态: **<font color=#dd3238>${currentBuild.result}</font>**",
                                "- 项目地址: [地址](${env.BUILD_URL})",
                                "- 构建日志: [日志](${env.BUILD_URL}console)",
                                 '- 进入页面: [http://43.138.159.33:65004/](http://43.138.159.33:65004/)',

                                '',
                                '---',
                                "- 执行人: ${currentBuild.getBuildCauses().shortDescription[0]}",

                                '---',
                                "- 持续时间:${currentBuild.durationString}",

                                '---'
                        ]
                )
            }
        }
    }
}
